package com.fun.frame.utils;

import com.fun.frame.Log;
import com.fun.frame.SourceCode;
import com.fun.profile.Constant;
import com.fun.utils.Time;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Output extends Constant {

    /**
     * 控制下一次json数据输出的key
     */
    static boolean onceKey = false;

    /**
     * 控制每次次json数据输出的key
     */
    static boolean alwaysKey = false;

    public static void setOnceKey() {
        Output.onceKey = true;
    }

    public static void setAlwaysKey() {
        Output.alwaysKey = true;
    }

    /**
     * 输出带有信息的异常
     *
     * @param object
     * @param e
     */
    public static void output(Object object, Exception e) {
        output(object);
        output(e);
    }

    /**
     * 输出异常
     *
     * @param e
     */
    public static void output(Exception e) {
        StackTraceElement[] stackTrace = e.getStackTrace();
        for (int i = 0; i < stackTrace.length; i++) {
            output(stackTrace[i]);
        }
    }

    /**
     * 输出，自带log方法,排除root用户使用输出
     *
     * @param text
     */
    public static void output(String text) {
        Log.log(LINE + Time.getNow() + TAB + text);
        if (!COMPUTER_USER_NAME.contains("root")) System.out.println(text);
    }

    /**
     * 输出数据
     *
     * @param n    第N项，用于for循环等，当n<0时不显示n
     * @param text
     */
    public static void outputData(int n, Object... text) {
        int length = text.length;
        if (length < 2 || length % 2 == 1) return;
        StringBuffer line = new StringBuffer();
        if (n >= 0) line.append("第" + (n + 1) + "个：" + TAB);
        for (int i = 0; i < length; i += 2) {
            String odd = text[i].toString();
            String even = text[i + 1].toString();
            line.append(odd + SourceCode.getFormat(even) + TAB);
        }
        output(line.toString());
    }

    /**
     * 参数化输出
     *
     * @param text
     * @param obj
     */
    public static void output(String text, Object... obj) {
        if (!text.contains(OUT_KEY)) {
            List<Object> objs = new ArrayList<>();
            objs.add(text);
            objs.addAll(Arrays.asList(obj));
            output(objs);
            return;
        }
        try {
            int length = obj.length;
            for (int i = 0; i < length; i++) {
                text = text.replaceFirst(OUT_KEY, obj[i].toString());
            }
            output(text);
        } catch (Exception e) {
            output("格式错误！", e);
        }
    }

    /**
     * 输出
     *
     * @param object
     */
    public static void output(Object... object) {
        if (object == null || object.length == 0 || object[0] == null) {
            output("怎么空了呢！");
            return;
        }
        if (object.length == 1) {
            if (object[0] instanceof List) {
                output(object[0].toString().replaceAll("\\[|\\]| ", EMPTY).split(","));
                return;
            }
            output(object[0].toString());
            return;
        }
        for (int i = 0; i < object.length; i++) {
            output("第" + (i + 1) + "个：" + object[i]);
        }
    }

    /**
     * 输出json数组
     *
     * @param jsonArray
     */
    public static void output(JSONArray jsonArray) {
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonObject.put(i + 1, jsonArray.get(i));
        }
        output(jsonObject);
    }

    /**
     * 输出数组
     *
     * @param arrays
     */
    public static void output(Number[] arrays) {
        if (arrays == null)
            return;
        int length = arrays.length;
        for (int i = 0; i < length; i++) {
            output(arrays[i] + "");
        }
    }

    /**
     * 输出json
     *
     * @param jsonObject json格式响应实体
     */
    public static void output(JSONObject jsonObject) {
        if (onceKey || alwaysKey) {
            onceKey = false;
            return;
        }
        if (jsonObject == null || jsonObject.isEmpty()) {
            output("json 对象是空的！");
            return;
        }
        String start = SourceCode.getManyString(SPACE_1, 3);
        String jsonStr = jsonObject.toString();// 先将json对象转化为string对象
        jsonStr = jsonStr.replaceAll("\\\\/", OR);
        int level = 0;// 用户标记层级
        StringBuffer jsonResultStr = new StringBuffer("＞  ");// 新建stringbuffer对象，用户接收转化好的string字符串
        for (int i = 0; i < jsonStr.length(); i++) {// 循环遍历每一个字符
            char piece = jsonStr.charAt(i);// 获取当前字符
            // 如果上一个字符是断行，则在本行开始按照level数值添加标记符，排除第一行
            if (i != 0 && '\n' == jsonResultStr.charAt(jsonResultStr.length() - 1)) {
                for (int k = 0; k < level; k++) {
                    jsonResultStr.append(start);
                }
            }
            switch (piece) {
                case ',':
                    // 如果是“,”，则断行
                    char last = jsonStr.charAt(i - 1);
                    if ("\"0123456789le]}".contains(last + EMPTY)) jsonResultStr.append(piece + LINE);
                    break;
                case '{':
                case '[':
                    // 如果字符是{或者[，则断行，level加1
                    jsonResultStr.append(piece + LINE);
                    level++;
                    break;
                case '}':
                case ']':
                    // 如果是}或者]，则断行，level减1
                    jsonResultStr.append(LINE);
                    level--;
                    for (int k = 0; k < level; k++) {
                        jsonResultStr.append(start);
                    }
                    jsonResultStr.append(piece);
                    break;
                default:
                    jsonResultStr.append(piece);
                    break;
            }
        }
        output("↘ ↘ ↘ ↘ ↘ ↘ ↘ ↘ json ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙");
        output(jsonResultStr.toString().replaceAll(LINE, LINE + "＞  "));
        output("↗ ↗ ↗ ↗ ↗ ↗ ↗ ↗ json ↖ ↖ ↖ ↖ ↖ ↖ ↖ ↖ ↖ ↖ ↖ ↖");
    }

}
